package com.shiguiwu.springboot3.service;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class RateLimiterService {
    private final ConcurrentMap<String, Bucket> cache = new ConcurrentHashMap<>();

    public boolean tryConsume(String key) {
        Bucket b = cache.computeIfAbsent(key, k -> Bucket.builder()
            .addLimit(Bandwidth.classic(10, Refill.greedy(10, Duration.ofSeconds(1))))
            .build());
        return b.tryConsume(1);
    }
}